package com.lagou.handler;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RegistryHandler {
    @Autowired
    private CuratorFramework curatorFramework;

    @Value("${rpc.server.host}")
    private String rpcServerHost;

    @Value("${rpc.server.port}")
    private Integer rpcServerPort;


    public void registToZK() {
        try {
            String path = "/provider/" + rpcServerHost + ":" + rpcServerPort;
            String s = curatorFramework.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(path, "init".getBytes());
            System.out.println("节点递归创建成功" + s);
            setResponseCost(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setResponseCost(long responseCost) {
        try {
            String path = "/provider/" + rpcServerHost + ":" + rpcServerPort;

            Stat stat = new Stat();
            curatorFramework.getData().storingStatIn(stat).forPath(path);
//            System.out.println("获取到的节点状态信息: " + stat);

            // 更新
            int version = curatorFramework.setData().withVersion(stat.getVersion()).forPath(path, (""+responseCost).getBytes()).getVersion();
//            System.out.println("当前最新版本是:" + version);
            System.out.println("更新"+rpcServerHost+":"+rpcServerPort+"的最后一次响应时间"+responseCost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
